package com.mahiru.mahiruaiagent.advisor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.advisor.api.*;
import org.springframework.ai.chat.model.MessageAggregator;
import reactor.core.publisher.Flux;

import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY;

/**
 * 自定义Advisor
 * 打印info日志 只输出单词用户提示词和响应
 *
 * @Author Enkidu
 * @Date 2025/7/3 23:53
 */
@Slf4j
public class MyLoggerAdvisor implements CallAroundAdvisor, StreamAroundAdvisor {

    public String getName() {
        return this.getClass().getSimpleName();
    }

    public int getOrder() {
        return 100;
    }

    private AdvisedRequest before(AdvisedRequest request) {
        // String chatId = (String) request.adviseContext().get(CHAT_MEMORY_CONVERSATION_ID_KEY);
        // log.info();
        log.info("AI Request : {}", request.userText());
        return request;
    }

    private void observeAfter(AdvisedResponse advisedResponse) {
        String chatId = (String) advisedResponse.adviseContext().get(CHAT_MEMORY_CONVERSATION_ID_KEY);
        log.info("AI Response : {}", advisedResponse.response().getResult().getOutput().getText());
    }

    public AdvisedResponse aroundCall(AdvisedRequest advisedRequest, CallAroundAdvisorChain chain) {
        advisedRequest = this.before(advisedRequest);
        AdvisedResponse advisedResponse = chain.nextAroundCall(advisedRequest);
        this.observeAfter(advisedResponse);
        return advisedResponse;
    }

    public Flux<AdvisedResponse> aroundStream(AdvisedRequest advisedRequest, StreamAroundAdvisorChain chain) {
        advisedRequest = this.before(advisedRequest);
        Flux<AdvisedResponse> advisedResponses = chain.nextAroundStream(advisedRequest);
        return (new MessageAggregator()).aggregateAdvisedResponse(advisedResponses, this::observeAfter);
    }
}
